

/*------------------------------------------------------------------------------
	1. Housekeeping
------------------------------------------------------------------------------*/

	*Run housekeeping code
		qui do ".../replication_package/housekeeping.do"

	*Write log
		log using "$log_loc/table_a2.log", text replace

	*Create Empty Tempfile to Store Regression Results
		tempfile table_a2
		save `table_a2', emptyok

/*------------------------------------------------------------------------------
	2. Clean Main Datasets
------------------------------------------------------------------------------*/
	forvalues year = 2017/2021 {
		*Import Data
		use "$data/childrens`year'.dta", clear

			/*Restrict Sample*/
				*Keep 1095 filings
					rename state_insurance state
					fmerge m:1 state using "$data/statelist.dta"
						assert _merge != 2 //Confirm that all 51 states are in dataset
						drop if _merge != 3

				*Keep if age_num is within the range
					keep if age_num >= 0 & age_num <= 16

				*Keep if kid died after end of year or is currently alive
					keep if `year'*10000+1231<death_date|death_date==0

				*Keep if months covered is possible
					keep if num_cov_ins > 0 & num_cov_ins <= 12

			/*Generate variables for table*/	
				*Generate outcome variable on claiming
					gen onreturn = file_inc != .

				*Generate a ct variable
					gen ct = 1

				*Generate variable for year
					gen year = `year'

/*------------------------------------------------------------------------------
	4. Carry Out Estimated Calculations
------------------------------------------------------------------------------*/

			/*Prepare backup data*/
				*Collapse to the by-state level		
					collapse (sum) ct onreturn, by(year state)

				*Adjust for Claiming Limits
					replace onreturn = onreturn * 1.0017029

				*Carry out Percent Claimed calculations
					gen perc_claimed = onreturn/ct

				*Keep key outcomes
					keep year state perc_claimed

		*Save results as a tempfile
		tempfile results_`year'
		save `results_`year'', replace
	}

	*Import and append the results from 2017 to 2021
	forvalues year = 2017/2021 {
		use `results_`year'', clear
		
		append using `table_a2'
		tempfile table_a2
		save `table_a2', replace
	}

		*Reshape wide, so that years are columns
			reshape wide perc_claimed, i(state) j(year)

		*Organize Before Export
			sort state
			order state perc_claimed2017 perc_claimed2018 perc_claimed2019 perc_claimed2020 perc_claimed2021 

	*Export Results
	export excel using "$output/table_backup_data.xlsx", first(var) sheet("tab_a2", replace)
